<template>
    <div>
        <div class="edit_wrap">
            <div class="return_button">
                <el-button icon="arrow-left" type="success" plain @click="goBack">返回</el-button>
            </div>
            <div class="edit_head">文章标题</div>
            <el-input v-model="title" placeholder="文章标题"></el-input>
            <div class="tag_wrap">
                <span>文章标签: </span>
                <el-tag class="tag_margin" :key="tag" v-for="tag in labels" :closable="true" :close-trasition="true"
                        @close="handleClose(tag)" type="primary">
                    {{ tag }}
                </el-tag>
                <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="mini"
                          @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
                </el-input>
                <el-button v-else class="button-new-tag" type="info" plain size="small" @click="showInput">添加标签
                </el-button>
            </div>
            <div class="edit_head">文章摘要</div>
            <el-input type="textarea" :autosize="{ minRows: 1, maxRows: 20}" placeholder="请输入文章摘要" v-model="gist">
            </el-input>
            <div class="edit_head">文章正文</div>
            <div class="markdown">
                <mavon-editor @imgAdd="$imgAdd" v-model="content" class="markdown" placeholder="请输入文章内容" ref=md
                              :ishljs="true" @imgDel="$imgDel" @change="change"/>
                <div class="clear"></div>
            </div>
            <div class="save_button">
                <el-button type="primary" @click="saveArticle">保存</el-button>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: 'articleEdit',
        data() {
            return {
                title: '',
                date: '',
                content: '',
                renderContent: '',
                gist: '',
                labels: [],
                inputVisible: false,
                inputValue: '',
                user: []
            }
        },
        mounted: function () {
            var userInfo = JSON.parse(localStorage.getItem('user'));
            if (!userInfo) {
                this.$message.success('用户未登录，请先登录!');
                this.$router.push('/admin/signin')
            } else {
                var screen_width = window.screen.width;

                if (screen_width < 767) {
                    this.$message.error('编辑文章请使用pc端操作!');
                    this.$router.push('/admin/articleList')
                } else {
                    this.user = userInfo;
                    if (this.$route.params.id) {
                        var _this = this;
                        this.$req({
                            method: "post",
                            url: 'http://49.235.28.88:3000/article/v1/articleDetail/' + _this.$route.params.id,
                            data: {}
                        }).then(function (res) {
                            var article = res.data.payload.article;
                            _this.title = article.title;
                            _this.date = article.created_date;
                            _this.content = article.content;
                            _this.gist = article.gist;
                            if (article.labels) {
                                _this.labels = article.labels.split(',');
                            }
                            _this.$message.success('获取文章详情成功!');
                        }).catch(function (e) {
                            _this.$message.error('服务器可能出现异常!');
                        });
                    }
                }
            }

        },
        methods: {
            $imgAdd(pos, $file) {
                // 第一步.将图片上传到服务器.
                var formData = new FormData();
                var _this = this;
                formData.append('avatar', $file);
                this.$req({
                    url: 'http://49.235.28.88:3000/users/upload_avatar',
                    method: 'post',
                    data: formData,
                    headers: {'Content-Type': 'multipart/form-data'},
                }).then((res) => {
                    if (res.data.status == 400) {
                        _this.$message.error(res.data.err);
                    } else if (res.data.status == 420) {
                        _this.$message.error(res.data.err.msg);
                    } else {
                        _this.$message.success('文章图片上传成功!');
                        let _res = 'http://pic.niyueling.cn:8000' + res.data.payload.avatar_path;
                        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
                        this.$refs.md.$img2Url(pos, _res);
                    }

                });
            },
            change(value, render) {
                this.renderContent = render;
            },
            $imgDel(pos) {
                delete this.img_file[pos];
            },
            // 保存文章
            saveArticle: function () {
                if (this.title.length === 0) {
                    this.$notify({
                        title: '警告',
                        message: '请输入文章标题',
                        type: 'warning'
                    });
                    return;
                }
                if (this.renderContent.length === 0) {
                    this.$notify({
                        title: '警告',
                        message: '请输入文章内容',
                        type: 'warning'
                    });
                    return;
                }
                if (this.gist.length === 0) {
                    this.$notify({
                        title: '警告',
                        message: '请输入文章简介',
                        type: 'warning'
                    });
                    return;
                }
                if (this.labels.length === 0) {
                    this.labels = '随笔';
                }
                if (this.$route.params.id) {
                    var _this = this;
                    // 更新文章
                    let obj = {
                        id: this.$route.params.id,
                        title: this.title,
                        content: this.renderContent,
                        gist: this.gist,
                        labels: this.labels
                    }

                    this.$req({
                        method: "post",
                        url: 'http://49.235.28.88:3000/article/v1/updateArticle',
                        data: obj
                    }).then(function (res) {
                        if (res.data.status == 200) {
                            _this.$message.success('修改文章成功!');
                            _this.$router.push('/admin/articleList');
                        } else {
                            _this.$message.error(res.body.err.msg);
                            _this.$router.push('/admin/articleList');
                        }
                    }).catch(function (e) {
                        _this.$message.error('服务器可能出现异常!');
                    });
                } else {
                    var _this = this;
                    let param = {
                        title: this.title,
                        content: this.renderContent,
                        gist: this.gist,
                        labels: this.labels,
                        status: 1,
                        author: this.user.username,
                        account: this.user.account,
                        app_sid: this.user.app_sid
                    }

                    this.$req({
                        method: "post",
                        url: 'http://49.235.28.88:3000/article/v1/saveArticle',
                        data: param
                    }).then(function (res) {
                        if (res.data.status == 400) {
                            _this.$message.error(res.body.err);
                        } else if (res.data.status == 420) {
                            _this.$message.error(res.body.err.msg);
                        } else {

                            _this.$message.success('文章发表成功!');
                            _this.$router.push('/admin/articleList');
                        }
                    }).catch(function (e) {
                        _this.$message.error('服务器可能存在异常!');
                    });
                }
            },
            // 保存成功后跳转至文章列表页
            goBack: function () {
                this.$router.push('/admin/articleList');
            },
            // element标签组件
            handleClose: function (tag) {
                this.labels.splice(this.labels.indexOf(tag), 1)
            },
            showInput: function () {
                this.inputVisible = true
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus()
                })
            },
            handleInputConfirm: function () {
                let inputValue = this.inputValue;
                if (inputValue) this.labels.push(inputValue);
                this.inputVisible = false;
                this.inputValue = '';
            }
        }
    }
</script>

<style scoped>
    .edit_wrap {
        padding: 40px;
        font-size: 16px;
        color: white;
    }

    .return_button {
        text-align: left;
        margin-bottom: 40px;
    }

    .tag_wrap {
        text-align: left;
        padding: 20px 0;
        color: white;
    }

    .tag_wrap .input-new-tag {
        width: 80px;
        height: 28px;
    }

    .edit_wrap textarea {
        outline: none;
        font-size: 16px;
    }

    .edit_head {
        margin: 20px 0;
        text-align: left;
    }

    .markdown {
        text-align: left;
        border: 1px solid #bfcbd9;
        -webkit-border-radius: 4px;
        -moz-border-radius: 4px;
        border-radius: 4px;
        width: 100%;
        height: 800px;
        vertical-align: top;
        background: #f5f7f9;
        overflow: hidden;
    }

    .markdown textarea {
        border: none;
        resize: none;
        /*不可拖动*/
    }

    .save_button {
        padding: 40px 0;
    }
</style>
